/**
 * 远光ECP平台3.0版本 http://www.ygsoft.com/ Grace [Gris Application Cloud-Computing
 * Extension]
 * Copyright(c) 1998 - 2020 YGSoft.Inc, All Rights Reserved
 * 
 * ecp.component.uploadManage.js
 * 
 * 上传组件管理界面
 * 
 * 变更版本：
 * Created by zhengxianwei@ygsoft.com 2016-07-25
 */
define(["jquery", "ecp.service", "ecp.utils", "ecp.component.dialog", "ecp.utils.i18n"],function($, $ecpService, utils, $window, i18n){
	
	//默认参数.
	var defaultOption = {
		upload : {
			beanId: "com.ygsoft.ecp.web.service.context.IFileAccessContext",
			method: "saveFile",
			jcls: "com.ygsoft.ecp.service.unstructure.EntityAttachmentSummaryVO",
			attachmentBeanId: "com.ygsoft.ecp.service.unstructure.service.context.IEntityAttachmentContext",
			attachmentQuery: "getSummariesByYwkey",
			attachmentUpdate: "updateSummariesBySummaries",
			attachmentBatchDel: "deleteSummaryAndDetailByResId",
			attachmentDel:"deleteSummaryAndDetailByResId"
		}
	};
	
	//窗口属性.
	var winOption = {
		title: i18n.upload.attatchManage,
		url : "/grm/ecp/webcore/components/upload/attachment.html",  //远程url 获取html片段
		fade : false,  //取消动画效果
        width : "600px",   //模态窗宽度 支持如 100% 600px
        maxHeight : "502px"  //模态窗body最大高度，超过时body内将出现滚动条
	}
	
	//上下文对象、组织、用户.
	var rs = $ecpService.RemoteService,
		attachmentVoList = [];
		
	/**
	 * 声明Webuploader对象.
	 */
	var UploadManage = function(control,option){
		if(!control || control.length === 0){return;}
		this.init(control,option);
		this.render();
	}
	
	/**
	 * 通过原型定义相关方法，比如渲染、赋值等等.
	 */
	UploadManage.prototype = {
		/**
		 * 初始化.
		 * @param {Object} control 占位符
		 * @param {Object} option 控件渲染配置属性
		 */
		init: function(control,option){
			this.control = control;
			this.option = $.extend(true, {}, defaultOption, option);
			var container = option.container;
			this.container = container;
		},
		
		/**
		 * 渲染
		 */
		render: function(){
			var me = this;
			//获得业务Id
			this.ywKey = this.getYwKey(); 
			//合并窗口属性
			var opt = $.extend(true,{},winOption,me.option.winOption,{
	            callback:function(container){
					//渲染表格
	            	me._renderWin(container);
            		me.container = container;
            		utils.loadLocale(i18n,container);
	            },
	            dialogHidden: function(){
	            	//关闭窗口时，如果删除了附件，但是没有点击“保存”按钮，此时要刷新面板
	            	if(me.doRefreshPanel){
	            		//保存的数据取子表数据
	        			var grid = $("#imageListGrid", me.container).qzzgrid(true);
	        			if(!grid){return;}
	        			var data = grid.value();
	        			me.option.closeCallBack && me.option.closeCallBack.call(me, data);
	            	}
	            	
	            },
	            showCloseButton:false,
	            offClick :true,  //取消点击非模态窗位置关闭窗口
	            otherButtons:[i18n.upload.close,i18n.upload.save],  //增加两个按钮
	            otherButtonStyles:['btn-link','btn-primary'], //按钮样式,
	            clickButton:function(sender, modal, index){
	            	if(index == 1){  //确定按钮
	            		me._saveBtn();
	            		modal.modal("hide");
	            	}
	            	if(index == 0){  //取消按钮
	            		modal.modal("hide");
	            	}
	            }
			});
			//弹窗控件渲染
			me.winContainer = $window.window(opt);
		},

		/**
		 * 渲染窗口内控件.
		 * @param {Object} container 容器
		 */
		_renderWin: function(container){
			var me = this,grid;
			require(["qzz.grid", "ecp.component.webUpload","ecp.component.loading"],function(qzzgrid, webUpload, PageLoading){
				me.pageLoading = new PageLoading({container : container});
				me.pageLoading.show();
				if(!grid){
					grid = $("#imageListGrid", container).qzzgrid({
				         "Align":"alClient",
				         "height":200,
//				         "pager":true,
				         "primaryKey":["resId"],
				         "multiselect":true,
				         "colNames":[i18n.upload.attachName, i18n.upload.attachType, i18n.upload.attachSize, i18n.upload.oparetor],
				         "colModels":[
				                      {"name":"title","frozen":true,"editable":false},
				                      {"name":"btype","editable":false},
				                      {"name":"bsize","editable":false},
				                      {"name":"operate","editable":false,"align":"center","filter":false}
			                      ]
				    });
					//修改状态时查询附件
					if(me.option.ywKey){
						me.queryFile(grid);
					}else{
						//清除进度条
						me.pageLoading.hide();
					}
					//绑定编辑后事件
					grid.bind("afterEditCell",function(PKeyName,fieldName,value){
						var data = grid.value();
						var curData = grid.getSelectedRowData(true);
						var resId = curData.resId;
						var oldTitle = curData._oldValue && curData._oldValue.title;
						if(utils.notEmpty(data)){
							$.each(data,function(){
								if(this.resId !== resId && this.title === value && this.btype === curData.btype){
									utils.notify(i18n.upload.somefilename);
									grid.setValue(fieldName,oldTitle);
									return false;
								}
							})
						}
					})
				}else{
					grid.value([]);
					me.pageLoading.hide();
				}
				//格式化操作列
				grid.dataSet.bind("onFormat_operate", function(node, fieldName, dataType, value, metaItem){
					return "<span style='cursor:pointer' title='"+ i18n.upload.del +"'><i class='fa fa-trash-o'></i></span>&nbsp;&nbsp;<span style='cursor:pointer' title='"+ i18n.upload.download +"'><i class='fa fa-download'></i></span>";
		        });
				grid.bind("onClick",function(node,fieldName){
					if(fieldName === "operate"){
						var ele = window.event.target;
						//删除
						if($(ele).hasClass("fa-trash-o")){
							me.deleteFile(node.data, grid);
						}else if($(ele).hasClass("fa-download")){
							//下载
							me.fileDownload(node.data);
						}
					}
				})
			    //绑定删除事件
			    $("#del",container).off("click").on("click", function(){
			    	 me.batchDeleteFile();
			    })
			    //上移
			    $("#moveup",container).off("click").on("click", function(){
			    	grid.moveRecord(-1);
			    })
			    $("#moveup",container).css("display","none");
			    //下移
			    $("#movedown",container).off("click").on("click", function(){
			    	grid.moveRecord(1);
			    })
			    $("#movedown",container).css("display","none"); 
			    //渲染上传组件
			    var opt = {};
			    opt.filesQueued = function(files, opt){
			    	me.saveFile(files, me.option, this.uploader, grid);
			    };
			    opt = $.extend(true,{},opt,me.option);
			    var uploadObj = $("#filePickerPlace",container);
			    var uploader = uploadObj.webUpload(opt);
				//绑定上传控件
				$("#upload",container).off("click").on("click", function(){
					uploadObj.find("label").click();
			    })
			 });
		},
		
		/**
		 * 保存上传的附件.
		 * 
		 * @param {Array} files 附件内容
		 * @param {Object} opt 属性
		 * @param {Object} uploader 上传对象
		 * @param {Object} grid 表格对象 
		 */
		saveFile: function(files, opt, uploader, grid){
			if(!files){return;}
			//校验单个附件大小是否超过20M  20 * 1024 * 1024=20971520
			for(var i = 0,j=files.length; i<j; i++){
				if(files[i].size > 20971520){
					utils.notify( i18n.upload.sizeError);
					return;
				}	
				//类型校验
				var fts = [];
				var fex = opt.fileExt;
				if($.isArray(fex)) {
					fts = fex;
				} else if(typeof fex == "string"){
					fts = [fex];
				}
				if($.inArray(files[i].ext.toLocaleLowerCase(), ["exe","dll"]) > -1
				    || fts.length > 0 && $.inArray(files[i].ext.toLocaleLowerCase(), fts) == -1){
					if(utils.notEmpty(opt.uploadExtMessage)) {
					    utils.notify(opt.uploadExtMessage);
					} else {
					    utils.notify(i18n.upload.uploadError + files[i].ext+ i18n.upload.typeError);
					}
					return;
				}
			}
			var me = this,
				params = [], 
				addData = [],
				resId, param, title, type, time,
				ywKey = me.getYwKey(),
				uploadOpt = me.option.upload,
				beanId = uploadOpt.beanId,
				dc = $ecpService.DataContextUtil,
				orgId = dc.getLoginOrgId(),
				userId = dc.getUserId(),
				method = uploadOpt.method;
			$.each(files,function(i,file){
				resId = Math.uuid();
				time = new Date().getTime();
				title = file.name.toUpperCase();
				title = title.substring(0,title.lastIndexOf("."));
				type = file.ext.toUpperCase();
	    		param = {
	        		   ywkey: ywKey,
	        		   resId: resId,
	        		   remark: "",
	        		   title: title,
	        		   bsize: file.size,
	        		   bsort: 2,
	        		   btype: type,
	        		   modelState: 4,
	        		   status: 0, 
	        		   userid: +userId,
	        		   attachmentDetailVO:{}
	    		};
	    		uploader.options.server = '/grm/ecp/webcore/FileAccessServlet?beanId='+beanId+'&method='+method+'&isMulti=true&'+
	           	'operParams=[null,'+ $.toJSON(param) +',"'+orgId+'"]&_token=' + $.cookie("ecpDataContext.tokenId") +'&tParam=' + time;
	    		//提交到服务端保存
	    		uploader.upload();
	    		var acVo = param;
	    		acVo.jcls = uploadOpt.jcls;
	    		acVo.modelState = 4;
	    		delete acVo.attachmentDetailVO;
	    		attachmentVoList.push(acVo);
	    		addData.push(acVo);
			})
    		//表格中插入数据
    		grid.addEcpRowData(addData);
		},
		
		/**
		 * 查询文件.
		 * @param {Object} grid 表格对象 
		 */
		queryFile: function(grid){
			var me = this,
				ywKey = this.getYwKey(),
				uploadOpt = this.option.upload,
				beanId = uploadOpt.attachmentBeanId,
				method = uploadOpt.attachmentQuery;
			if(!beanId || !method){
				me.pageLoading.hide();
				return;
			}
			rs.doPostAsync(beanId, method, [ywKey], function(res){
				if (res.isError()) {
					utils.notify(i18n.upload.delError + res.data);
					me.pageLoading.hide();
					return;
				} else {
					//给表格赋值
					var data = res.data;
					if(utils.notEmpty(data)){
						attachmentVoList = data;
						grid.value(data);
					}
					me.pageLoading.hide();
				}
			});
		},
		
		/**
		 * 删除单个文件
		 * @param {Object} node 行数据对象 
		 * @param {Object} grid 表格对象 
		 */
		deleteFile: function(node,grid){
			var resId = node && node.resId;
	        if(!resId){return;}
	        var me = this,
				opt = me.option,
				uploadOpt = opt.upload,
				beanId = uploadOpt.attachmentBeanId,
				method = uploadOpt.attachmentDel;
			if(!beanId || !method){
				return;
			}
			$window.dialog({
                title: i18n.upload.delTip,   //模态窗标题
                content: i18n.upload.delSure, //模态窗内容
                isTip:true,//标准的提示窗口
                showCloseButton:false,  //不显示关闭按钮
                otherButtons:[i18n.upload.cancel, i18n.upload.sure],  //增加两个按钮
                otherButtonStyles:['btn-link','btn-primary'], //按钮样式,
                clickButton:function(sender, modal, index, notify){
                   if(index == 1){  //确定按钮
						rs.doPostAsync(beanId, method, [resId], function(res){
							if (res.isError()) {
									utils.notify(i18n.upload.delError + res.data);
							}else{
								utils.notify(i18n.upload.delSuccess);
								grid.delRecord(resId);
								me.doRefreshPanel = true;
							}
						})
                   }
                   modal.modal("hide"); //关闭模态窗
                }
           });
		},
		
		/**
		 * 批量删除已保存的文件（文件上传成功了，但是单据没有保存，这时候要删除之前上传的文件）
		 */
		batchDeleteFile: function(){
			var me = this,
				opt = me.option,
				uploadOpt = opt.upload,
				beanId = uploadOpt.attachmentBeanId,
				method = uploadOpt.attachmentBatchDel;
			if(!beanId || !method){
				return;
			}
			var grid = $("#imageListGrid", me.container).qzzgrid(true);
			if(!grid){return;}
			var selData = grid.getSelectedRowData();
	    	if(utils.notEmpty(selData)){
	    		$window.dialog({
	                title: i18n.upload.delTip,   //模态窗标题
	                content: i18n.upload.batchDelSure, //模态窗内容
	                isTip:true,//标准的提示窗口
	                showCloseButton:false,  //不显示关闭按钮
	                otherButtons:[i18n.upload.cancel, i18n.upload.sure],  //增加两个按钮
	                otherButtonStyles:['btn-link','btn-primary'], //按钮样式,
	                clickButton:function(sender, modal, index, notify){
	                   if(index == 1){  //确定按钮
	                	   	var flag = false;
		       	    		$.each(selData,function(){
		       	    			//删除数据库中的附件信息
		       		    		rs.doPostAsync(beanId,method,[this.resId], function(res){
		       						if (res.isError()) {
		       							utils.notify(i18n.upload.delError + res.data);
		       						}else{
		       							if(flag === true){return;}
		       							//批量删除表格中选中记录
		       							grid.eachChecked(function(){
		       								grid.delRecord();
		       							})
		       							//删除attachmentVoList中的数据
		       							$.each(attachmentVoList,function(){
		       								var vo = this;
		       								$.each(selData,function(){
		       									if(this.gid == vo.resId){
		       										attachmentVoList.remove(vo);
		       									}
		       								})
		       							})
		       							utils.notify(i18n.upload.delSuccess);
		       							flag = true;
		       							me.doRefreshPanel = true;
		       						}
		       		    		})
		       	    		})
	                   }
	                   modal.modal("hide"); //关闭模态窗
	                }
	           });
	    		
	    	}else{
	    		utils.notify(i18n.upload.selectAttatch);
	    	}
		},
		
		/**
		 * 保存.
		 */
		_saveBtn: function(){
			var me = this,
				opt = me.option,
				uploadOpt = opt.upload,
				beanId = uploadOpt.attachmentBeanId,
				method = uploadOpt.attachmentUpdate;
			if(!beanId || !method){
				return;
			}
			//保存的数据取子表数据
			var grid = $("#imageListGrid", me.container).qzzgrid(true);
			if(!grid){return;}
			grid.each(function(node){
				this.setValue("bsort", this.getIndex());
			}, function() {
				var data = grid.value();
				if(utils.notEmpty(data)){
					//修改附件 
					rs.doPostAsync(beanId, method, [data], function(res){
						if (res.isError()) {
							//return;
						}else{
							me.doRefreshPanel = false;
							opt.closeCallBack && opt.closeCallBack.call(me, data);
						}
						attachmentVoList = [];
					});
				}
			});			
		},
		
		/**
		 * 文件下载.
		 * @param {Object} file 要下载的文件对象
		 */
		fileDownload: function(file) {
			var fileType = file["btype"],
				size = parseInt(file["bsize"]) * 1024,
				dc = $ecpService.DataContextUtil,
				userId = dc.getUserId(),
				orgId = dc.getLoginOrgId();
			var url = utils.getAttachmentDownLoadURL(file, userId, orgId);
			var fileName = file["title"] + '.' + fileType;
			if (fileType) {
				fileType = fileType.toUpperCase();
			}
			// 在封装的客户端调用
			var isNodeWebkit = utils.isNodeWebkitBrower();
			var isChrome = utils.isChromeBrower();
			if ((isNodeWebkit || isChrome) && /(PPT|PPTX|XLS|XLSX|DOC|DOCX)/i.test(fileType)) {
				try {
					var serverAddress = utils.getLocalAddress();
					// office用预览地址打开
					var previewUrl = file.previewUrl;
					if (previewUrl) {
						if (previewUrl.indexOf("/") === 0) {
							previewUrl = serverAddress + previewUrl;
						} else {
							previewUrl = serverAddress + "/" + previewUrl;
						}
					}
					var obj = this.getNpapiObj();
					obj.runExe("iexplore.exe\0", previewUrl+ "\0");
				} catch (e) {
					this.downloadFile(fileName, url);
				}
				return;
			}
			this.downloadFile(fileName, url);
		},
		
		getNpapiObj: function(id, type) {
			var dllToolObj = null;
			if (window.addEventListener) {
				dllToolObj = document.getElementById("dlltool");
				if (dllToolObj == null) {
					dllToolObj = document.createElement("embed");
					dllToolObj.id = "dlltool";
					dllToolObj.type = "application/rpygtooljs";
					dllToolObj.width = 1;
					dllToolObj.height = 1;
					var ddd = document.getElementsByTagName("BODY");
					ddd[0].appendChild(dllToolObj);
				}
			}
			return dllToolObj;
		},
		
		/**
		 * 下载.
		 * @param {String} name 文件名称
		 * @param {String} url 文件下载地址
		 */
		 downloadFile: function (name, url) {
			if (isNaN(utils.getIEVersion())) {
				var doc = document;
				dlf = doc.getElementById("fileDownloadFrame");
				if (dlf == null) {
					dlf = doc.createElement("iframe");
					dlf.id = "fileDownloadFrame";
					dlf.style.display="none";
					doc.body.appendChild(dlf);
				}
				dlf.src = url;
			} else {
				window.open(url);
			}
		},
		
		/**
		 * 获取ywKey.
		 */
		getYwKey: function(){
			var opt = this.option,
				ywKey = opt.ywKey;
			if(this.ywKey){
				ywKey = this.ywKey;
			}else if(!utils.notEmpty(ywKey)){
				this.ywKey = ywKey = Math.uuid();
			}
			return ywKey;
		}
	};
	(function($) {
		var old = $.fn.uploadManage;
		$.fn.uploadManage = function(option){
			var me = this;
			option = option || {};
			var type = typeof(option);
			//如果第一个参数传入的是对象或空则初始化空件，如果传入的是字符串，则认为是调用里面的内部方法。
			if (type === "object") {
				var eus = [];
				this.each(function() {
					var instanceOption = $.extend({}, option, true);
					var instance = new UploadManage($(this), instanceOption);
					this.uploadManage = instance;
					eus.push(instance);
				});
				if(eus.length === 1){
					eus = eus[0];
				}
				return eus;
			} else if (type === "string") {
				var args = Array.prototype.slice.call(arguments, 1);
				if (UploadManage.prototype[option]) {
					return UploadManage.prototype[option].call(args);
				}
			} else if (option === true) {
				return me[0] && me[0].uploadManage;
			}
		};
		$.fn.uploadManage.Constructor = UploadManage;
		$.fn.uploadManage.noConflict = function() {
			$.fn.uploadManage = old;
			return this;
		};
	}(jQuery));
	return UploadManage;
		
});